from django.shortcuts import render, HttpResponseRedirect,redirect
from django.contrib import messages
from django.contrib import auth
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.http import JsonResponse
from django.views import generic
from django.views.decorators.csrf import csrf_exempt
from rest_framework_jwt.settings import api_settings

# Create your views here.
from .forms import UserForm, loginForm, ProfileForm
from .models import Ouser,UserPlan
import re,json,requests


class OpenId:
    def __init__(self, jscode):
        self.url = 'https://api.weixin.qq.com/sns/jscode2session'
        self.app_id = settings.WECHAT['appid']
        self.app_secret = settings.WECHAT['secret']
        self.jscode = jscode

    def get_openid(self):
        url = self.url + "?appid=" + self.app_id + "&secret=" + self.app_secret + "&js_code=" + self.jscode + "&grant_type=authorization_code"
        res = requests.get(url)
        try:
            openid = res.json()['openid']
            session_key = res.json()['session_key']
        except KeyError:
            return 'fail'
        else:
            return openid, session_key



@csrf_exempt
def GetOpenIdView(request):
    data = json.loads(request.body)
    jscode = data['jscode']

    openid, session_key = OpenId(jscode).get_openid()
    print(openid,session_key)
    return JsonResponse({
        'openid': openid,
        'session_key': session_key
    })


##微信小程序登录
@csrf_exempt
def login_or_create_account(request):
    data = json.loads(request.body)
    print(data)
    openid = data['openid']
    nickname = data['nickname']
    avatar_url = data['avatar_url']
    gender = data['gender']

    try:
        user = Ouser.objects.get(username=openid)
    except Ouser.DoesNotExist:
        user = None

    if user:
        user = Ouser.objects.get(username=openid)
    else:
        user = Ouser.objects.create(
            username=openid,
            password=openid,
            # nickname=nickname,
            avatar=avatar_url,
            # gender=gender
        )

    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
    payload = jwt_payload_handler(user)
    token = jwt_encode_handler(payload)
    res = {
        'status': 'success',
        # 'nickname': user.nickname,
        'user_id': user.id,
        'token': token
    }
    return JsonResponse(res)


# 注册
@csrf_exempt
def register_view(request):
    context = {}
    if request.method == 'POST':
        form = UserForm(request.POST)
        next_to = request.POST.get('next', 0)
        if form.is_valid():
            # 获得表单数据
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            password2 = form.cleaned_data['password2']
            email = form.cleaned_data['email']
            context = {'username': username, 'pwd': password, 'email': email}
            if password.isdigit():
                context['pwd_error'] = 'nums'
                return render(request, 'account/signup.html', context)
            if password != password2:
                context['pwd_error'] = 'unequal'
                return render(request, 'account/signup.html', context)

            # 判断用户是否存在
            user = Ouser.objects.filter(username=username)
            Email = Ouser.objects.filter(email=email)
            pwd_length = len(password)
            if pwd_length < 8 or pwd_length > 20:
                context['pwd_error'] = 'length'
                return render(request, 'account/signup.html', context)

            user_length = len(username)

            if user_length < 5 or user_length > 20:
                context['user_error'] = 'length'
                return render(request, 'account/signup.html', context)
            if user:
                context['user_error'] = 'exit'
                return render(request, 'account/signup.html', context)
            if not re.match('^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$', email):
                context['email_error'] = 'format'
                return render(request, 'account/signup.html', context)
            if Email:
                context['email_error'] = 'exit'
                return render(request, 'account/signup.html', context)
            # 添加到数据库（还可以加一些字段的处理）
            user = Ouser.objects.create_user(username=username, password=password, email=email)
            user.save()
            # comment_user = CommentUser.objects.create(nickname=username, email=email)
            # comment_user.save()
            user = auth.authenticate(username=username, password=password)

            # 添加到session
            request.session['username'] = username
            request.session['uid'] = user.id
            request.session['email'] = email
            request.session['nick'] = ''

            # 调用auth登录
            auth.login(request, user)
            # 重定向到首页
            if next_to == '':
                next_to = '/'
            return redirect(next_to)
    else:
        next_to = request.GET.get('next', '/')
        context = {'isLogin': False}
        context['next_to'] = next_to
    # 将req 、页面 、以及context{}（要传入html文件中的内容包含在字典里）返回
    return render(request, 'account/signup.html', context)


# 登陆
@csrf_exempt
def login_view(request):
    context = {}
    if request.method == 'POST':
        print(request.body)
        print(json.loads(request.body))
        data = json.loads(request.body)

        if data['code']:
            user = Ouser.objects.filter(id=1).first()
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            res = {
                'status': 'success',
                'nickname': user.username,
                'user_id': user.id,
                'token': token
            }
            return JsonResponse(res)
        form = loginForm(request.POST)
        next_to=request.POST.get('next','/')

        remember = request.POST.get('remember', 0)
        if form.is_valid():
            # 获取表单用户密码
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            context={'username':username,'pwd':password}
            # 获取的表单数据与数据库进行比较
            user = authenticate(username = username,password = password)
            if next_to=='':
                next_to='/'
            if user:
                if user.is_active:
                    # 比较成功，跳转index
                    auth.login(request,user)
                    request.session['username'] = username
                    request.session['uid'] = user.id
                    request.session['nick'] = None
                    request.session['tid'] = None
                    reqs = HttpResponseRedirect(next_to)
                    if remember != 0:
                        reqs.set_cookie('username',username)
                    else:
                        reqs.set_cookie('username', '', max_age=-1)
                    return reqs
                else:
                    context['inactive'] = True
                    return render(request, 'account/login.html', context)
            else:
                # 比较失败，还在login
                context['error'] = True
                return render(request, 'account/login.html', context)
    else:
        next_to = request.GET.get('next', '/')

        context['next_to'] = next_to

    return render(request, 'account/login.html', context)


# 登出
def logout_view(request):
    # 清理cookie里保存username
    next_to = request.GET.get('next', '/')
    if next_to == '':
        next_to = '/'
    auth.logout(request)
    return redirect(next_to)



@login_required
def profile_view(request):
    return render(request, 'oauth/profile.html')


@login_required
@csrf_exempt
def change_profile_view(request):
    if request.method == 'POST':
        # 上传文件需要使用request.FILES
        form = ProfileForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            # 添加一条信息,表单验证成功就重定向到个人信息页面
            messages.add_message(request, messages.SUCCESS, '个人信息更新成功！')
            return redirect('accounts:profile')
    else:
        # 不是POST请求就返回空表单
        form = ProfileForm(instance=request.user)
    return render(request, 'oauth/change_profile.html', context={'form': form})


def publish_view(request):
    return render(request, 'oauth/publish.html')



def create_plan(request):
    if request.method == 'POST':
        try:
            user_plan = UserPlan.objects.create(
                user=Ouser.objects.get(id=request.POST.get('user')),
                title=request.POST.get('title'),
                content=request.POST.get('content'),
                start_time=request.POST.get('start_time'),
                end_time=request.POST.get('end_time'),
            )
            attention = request.POST.getlist('attention')
            if attention:
                user_plan.attention.set(attention)
            return JsonResponse({'code': 200, 'result': True, 'msg': '数据保存成功！'})
        except Exception as e:
            return JsonResponse({'code': 500, 'result': False, 'msg': '数据保存失败！{}'.format(e)})
    users = Ouser.objects.exclude(id__in=[request.user.id])
    return render(request, 'account/create_plan.html', locals())
#
#
def plan_info(request, pk):
    user_plan = UserPlan.objects.prefetch_related('attention').get(id=pk)
    if request.method == 'GET':
        users = Ouser.objects.exclude(id__in=[request.user.id])
        return render(request, 'account/plan_info.html', locals())
    elif request.method == 'POST':
        try:
            user_plan.status = 1 if request.POST.get('status') else 0
            user_plan.title = request.POST.get('title')
            user_plan.content = request.POST.get('content')
            user_plan.start_time = request.POST.get('start_time')
            user_plan.end_time = request.POST.get('end_time')
            attention = request.POST.getlist('attention')
            if attention:
                user_plan.attention.set(attention)
            else:
                user_plan.attention.clear()
            user_plan.save()
            return JsonResponse({'code': 200, 'result': True, 'msg': '数据保存成功！'})
        except Exception as e:
            return JsonResponse({'code': 500, 'result': False, 'msg': '数据保存失败！{}'.format(e)})
    elif request.method == 'DELETE':
        try:
            user_plan.delete()
            return JsonResponse({'code': 200, 'result': True, 'msg': '数据删除成功！'})
        except Exception as e:
            return JsonResponse({'code': 500, 'result': False, 'msg': '数据删除失败！{}'.format(e)})